package com.hx.miniblog.interceptor;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.hx.miniblog.exception.MiniBlogException;
import com.hx.miniblog.util.constant.Constant;
import com.hx.miniblog.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author wenhao hu
 * @title:
 * @projectName miniBlog
 * @description: TODO
 * @date 2021/12/2816:54
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result<?> exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        if(e instanceof MiniBlogException){
            MiniBlogException exception = ((MiniBlogException) e);
            return Result.error(exception.getCode(),exception.getMsg());
        }
        else if (e instanceof BindException) {
            BindException exception = (BindException) e;
            List<ObjectError> errors = exception.getAllErrors();
            Result<?> result = new Result<>();
            return  result.error500(Constant.HTTP_CODE.FAIL,
                    errors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                            .collect(Collectors.joining(Constant.STRING_POOL.douhao)));
        }else if (e instanceof TokenExpiredException){
            return Result.error(Constant.HTTP_CODE.FAIL,Constant.MESSAGE.TOKEN_EXPIRE);
        }
        return new Result<>().error500(Constant.HTTP_CODE.NET_ERROR,Constant.MESSAGE.NET_ERROR_MESSAGE);
    }
}
